import Vue from 'vue'
// import Vuex from 'vuex'
import Vuex from '../vuex/index'
// import logger from 'vuex/dist/logger.js'

Vue.use(Vuex)
// 插件
// function logger() {
//   return function (store) {
//     let prevState = JSON.stringify(store.state)
//     store.subscribe((mutations,state)=>{
//       console.log('prevState:'  +prevState)
//       console.log(mutations)
//       console.log( 'currentState:'+ JSON.stringify(state))
//       prevState = JSON.stringify(state)
//     })
//   }
// }
function persists() {
  return function (store) {
    if(localStorage.getItem('VUEX:STATE')){
      let localState = JSON.parse(localStorage.getItem('VUEX:STATE')) 
      store.replaceState(localState)
    }
      store.subscribe((mutations,state)=>{
        //状态发生变化就存localStorage
        localStorage.setItem('VUEX:STATE',JSON.stringify(state))
      })
  }
}

export default new Vuex.Store({
  plugins:[
    // logger()
    persists()
  ],
  state: {
    name:'hl',
    age:1,
    myAge:2,
  },
  mutations: {
    changeAge(state,payload){
      state.age =state.age + payload
    }
  },
  getters:{
    myAge(state){
      return state.age +1 
    }
  },
  actions: {
    changeAge({commit},payload){
      commit('changeAge',payload)
    },
    changeAgeAsync({commit},payload){
      commit('changeAge',payload)
    }
  },
  modules: {
    a: {
      namespaced: true,
      state: {
          name: 't1',
          age: 10
      },
      // 所有的getters 都会被合并到跟上
      getters: { // 首页一个模块 home 订单页一个模块 order  用户一个模块 user
          myAge(state) {
              return state.age + 20;
          }
      },
      mutations: {
          changeAge(state, payload) {
              state.age += payload
          }
      },
      modules: {
          c: {
              namespaced: true,
              state: {
                  age: 100
              },
              mutations: {
                  changeAge(state, payload) {
                      state.age += payload
                  }
              },
              modules: {
                  d: {
                      namespaced: true,
                      state: {
                          age: 100
                      },
                  }
              }
          }
      }
  },
  }
})
